package it.unibo.iss.domotica;

import it.unibo.is.domoticaContact.DomoticaContact;
import it.unibo.is.domoticaContact.UsrcmdContact;
import it.unibo.iss.domotica.converter.DomoticaJsonConverter;
import it.unibo.iss.domotica.edDomain.Elettrodomestico;
import it.unibo.iss.domotica.edDomain.StatoED;
import it.unibo.platform.lindaLike.LindaLike;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class UsrCmdActivity extends UsrCmdActivitySupport {
	
	private ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
	private ArrayList<Elettrodomestico> elettrodomestici = new ArrayList<Elettrodomestico>();
	private ArrayList<Elettrodomestico> listEdSuperflui;
	private ListView listViewEd;
	private SimpleAdapter adapter;
	private Usrcmd usrcmd;
	private UsrCmdDialogBuilder builder;
	private Dialog progressDialog;
	private static final String TAGFORLOG = "UsrCmdActivity";
	private Handler handler = new Handler() {
    	@Override
		public void handleMessage(Message msg) {
    		super.handleMessage(msg);
    		
			updateDataListViewEd();
		}
	};
	private Timer timer;
	private static final int UPDATE_FREQUENCY = 2000;
	private UpdateListEdThread updateListEdThread;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		usrcmd = new Usrcmd();
		builder = new UsrCmdDialogBuilder(this);
		
		DomoticaContact.go();
		
		String[] from={"edStateImage", "edName", "edState", "edConsumption"}; 		//dai valori contenuti in queste chiavi
        int[] to={R.id.edStateImage, R.id.edNameText, R.id.edStateText, R.id.edConsumptionText};	//agli id delle view
        
        //costruzione dell adapter
        adapter = new SimpleAdapter(
                        getApplicationContext(),
                        data,//sorgente dati
                        R.layout.itemed_layout, 	//layout contenente gli id di "to"
                        from,
                        to);
        
        //utilizzo dell'adapter
        listViewEd = (ListView)findViewById(R.id.listEdView);
        listViewEd.setAdapter(adapter);
        updateDataListViewEd();
                
        registerForContextMenu(listViewEd);
        
        
		timer = new Timer();
		updateListEdThread = new UpdateListEdThread(this);
		
		timer.schedule(updateListEdThread, 0, UPDATE_FREQUENCY);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		return builder.onCreateDialog(id);
	}
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch(id) {
			case UsrCmdDialogBuilder.LISTEDSUPERFLUI_DIALOG:
//				((ListEdSuperfluiDialog)dialog).setListEdSuperflui(listEdSuperflui);
				break;
			
			case UsrCmdDialogBuilder.PROGRESSLOADINGED_DIALOG:
				progressDialog = dialog;
				break;
		}
	}
	
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		if (v.getId()==R.id.listEdView) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			menu.setHeaderTitle(elettrodomestici.get(info.position).getNome());
			String[] menuItems = getResources().getStringArray(R.array.submenu);
			for (int i = 0; i<menuItems.length; i++) {
				menu.add(Menu.NONE, i, i, menuItems[i]);
			}
		}
	}
	
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		
		int menuItemIndex = item.getItemId();
		String[] menuItems = getResources().getStringArray(R.array.submenu);
		String menuItemName = menuItems[menuItemIndex];
		String listItemName = elettrodomestici.get(info.position).getNome();

//		TextView text = (TextView)findViewById(R.id.footer);
//		text.setText(String.format("Selected %s for item %s", menuItemName, listItemName));
		
		show(String.format("Selected %s for item %s", menuItemName, listItemName));
		
		if(menuItemName.compareTo("Power On") == 0) {
				powerOn(listItemName);
				updateDataListViewEd();
		}
		else if(menuItemName.compareTo("Power Off") == 0) {
				powerOff(listItemName);
				updateDataListViewEd();
		}
		
		return super.onContextItemSelected(item);
	}
	

	protected void updateListEd() {
//		showDialog(UsrCmdDialogBuilder.PROGRESSLOADINGED_DIALOG);
//		progressDialog = ProgressDialog.show(this, "", "Loading household appliances list...", true, false);

		elettrodomestici = usrcmd.updateListEd();
		if(usrcmd.isError()) {
			show("Update failed: " + usrcmd.getErrorMessage());
		}
//		else {
//			updateDataListViewEd();
//		}
		
//		progressDialog.dismiss();
	}
	
	
	protected void powerOn(String edName) {
		ArrayList<Elettrodomestico> listEdSuperflui = usrcmd.powerOn(edName);
		
		if(usrcmd.isError()) {
			show(usrcmd.getErrorMessage());
		}
		else {
			if(listEdSuperflui != null) {
				builder.setListEdSuperflui(listEdSuperflui);
				showDialog(UsrCmdDialogBuilder.LISTEDSUPERFLUI_DIALOG);
			}
		}
		
//		listEdSuperflui = elettrodomestici;
//		builder.setListEdSuperflui(listEdSuperflui);
//		showDialog(UsrCmdDialogBuilder.LISTEDSUPERFLUI_DIALOG);
	}

	
	protected void powerOff(String edName) {
		if(usrcmd.powerOff(edName)) {
			show("Power Off succeded");
		}
		else {
			show("Power Off failed: " + usrcmd.getErrorMessage());
		}
	}
	
	
	protected void updateDataListViewEd() {
		CommonUtilities.updateDataSourceListEd(this.elettrodomestici, this.data);
		adapter.notifyDataSetChanged();
	}
	
	public void onPowerOffSuperfluoClick(Elettrodomestico ed) {
		show("Selected: " + ed);
		powerOff(ed.getNome());
	}
	
	public void onAbortPowerOffSuperfluoClick() {
		if(usrcmd.forwardAbortPowerOffSuperflui()) {
			show("Operation aborted");
		}
		else {
			show("Error while aborting operation: " + usrcmd.getErrorMessage());
		}
	}
	
	private class UpdateListEdThread extends TimerTask {

		private UsrCmdActivity parent;
		
		public UpdateListEdThread(UsrCmdActivity parent) {
			this.parent = parent;
		}
		
		@Override
		public void run() {
			parent.updateListEd();
			handler.sendEmptyMessage(0);
		}
		
	}
}
